import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { GetToken } from "../utils/Token";
let routes: Array<RouteRecordRaw> = [
  {
    path: "/error",
    name: "/error",
    component: () => import("../view/error.vue"),
  },
  {
    path: "/",
    name: "/",
    component: () => import("../view/index/index.vue"),
  },
  {
    path: "/login",
    name: "/login",
    component: () => import("../view/index/login.vue"),
  },
  {
    path: "/AddBuddy",
    name: "/AddBuddy",
    component: () => import("../view/data/AddBuddy.vue"),
  },
  {
    path: "/ApplyBuddy",
    name: "/ApplyBuddy",
    component: () => import("../view/data/ApplyBuddy.vue"),
  },
  {
    path: "/BuddyList",
    name: "/BuddyList",
    component: () => import("../view/index/BuddyList.vue"),
  },
  {
    path: "/Chat",
    name: "/Chat",
    component: () => import("../view/data/Chat.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});
router.beforeEach((to, from, next) => {
  if (from.name) {
  }
  if (!to.name) {
    next({ name: "/error" });
  }
  // 如果token存在
  if (GetToken()) {
    // 当token存在判断当时是否前往登录页面
    if (to.name == "/login") {
      next({ name: "/" });
    } else {
      next();
    }
  } else {
    // 当token不存在的时候
    if (to.name == "/error") {
      next();
    } else if (to.name != "/login") {
      next({ name: "/login" });
    } else {
      next();
    }
  }
});
export default router;
